package javaBase.javaTimerTask;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author admin 对于 Timer 的缺陷，我们可以考虑 ScheduledThreadPoolExecutor 来替代。 Timer
 *         是基于绝对时间的，对系统时间比较敏感，而 ScheduledThreadPoolExecutor 则是基于相对时间；Timer
 *         是内部是单一线程，而 ScheduledThreadPoolExecutor 内部是个线程池，所以可以支持多个任务并发执行。
 *
 */
public class ScheduledExecutorTest {
	private ScheduledExecutorService scheduExec;
	public long start;

	ScheduledExecutorTest() {
		this.scheduExec = Executors.newScheduledThreadPool(2);
		this.start = System.currentTimeMillis();
	}

	public void timerOne() {
		scheduExec.schedule(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println("timerOne the time:"
						+ (System.currentTimeMillis() - start));
				throw new RuntimeException();
				/*try {
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
			}
		}, 1000, TimeUnit.MILLISECONDS);
	}

	public void timerTwo() {
		scheduExec.schedule(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println("timerTwo the time:"
						+ (System.currentTimeMillis() - start));
			}
		}, 3000, TimeUnit.MILLISECONDS);
	}

	public static void main(String[] args) {
		ScheduledExecutorTest set = new ScheduledExecutorTest();
		set.timerOne();
		set.timerTwo();
	}
}
